<script setup>
import { ElMessage,ElMessageBox  } from 'element-plus'
import DialogYaml from '../components/DialogYaml.vue';
import { obj2Yaml } from '../../utils/utils';
import StringOrNumber from '../components/StringOrNumber.vue';
import CreateOrEditFrame from '../components/CreateOrEditFrame.vue'
import { ref ,onBeforeMount, reactive, toRefs, computed} from 'vue';
import { da } from 'element-plus/es/locales.mjs';
import { listHandler } from '../../api/generic.js';
import { deleteTableRow } from '../../utils/utils';
import Table from '../components/Table.vue';
import { object2List,list2Object } from '../../utils/utils';
// import DialogYaml from '../components/DialogYaml.vue';
// import { obj2Yaml } from '../../utils/utils';
import  CodeMirror  from '../components/CodeMirror.vue';
import { createOrUpdateByYamlHandler as createHandler } from '../../api/tools';
import {useRouter} from 'vue-router'
const router = useRouter()

const data = reactive({
  clusterId: '',
  options: {
    method: "Create",
    },
})

let yamlContent = ref('')

const submitRollback = (msg)=>{ 
  ElMessageBox.confirm(
    msg,
    '执行结果',
    {
      confirmButtonText: '查看列表',
      cancelButtonText: '返回',
      type: 'success',
    }
  )
    .then(() => {
      //跳转到对应的列表页
      router.replace({
        path: '/pv/list',
        query: {
          clusterId: data.clusterId,
        }
      })
    })
    .catch(() => {
      return
    })
}

const submitHandler = (tag) => {
  console.log('tag:', tag)
  console.log('item:', data.item)
  //把list转成object
  data.item.metadata.labels = list2Object(data.options.labelList)
  data.item.metadata.annotations = list2Object(data.options.annotationsList)
  if (tag == 'yaml') {
    // 首先要把json转成yaml
    const yamlData = obj2Yaml(data.item)
    yamlContent.value = yamlData
    showDetail.value = true
  } else {
    const postData = {
      clusterId: data.clusterId,
      item: data.item,
    }
    if (props.method != "Update") {
        // 创建用户，异步的
        createHandler(postData).then((response)=>{
          // console.log("response:", response)
          // ElMessage({
          //         message: response.data.message,
          //         type: 'success',
          // })
          submitRollback(response.data.message)
          // loading.value = false
          // emits('rollback')
        })
  } else {
      // 创建用户，异步的
      updateHandler(postData).then((response)=>{
          // console.log("response:", response)
          // ElMessage({
          //         message: response.data.message,
          //         type: 'success',
          // })
          submitRollback(response.data.message)
      })
    }
  }

}

const submit = ()=> {
    if(yamlContent.value == ''){
      ElMessage.error("请输入Yaml数据")
      return
    }else{
      ElMessageBox.confirm(
    `你确定要修改集群${data.clusterId}的数据吗？`,
    '',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
        //创建资源或者更新资源
        const postData = {
        clusterId: data.clusterId,
        yaml: yamlContent.value,
        method: data.options.method
      }
      createHandler(postData).then((res)=>{
        //换行<br/>
        let msgTemp = res.data.message
       const msg =  msgTemp.replace("\n", "<br/>")
        ElMessageBox.confirm(
          msg,
      '提交成功',
      {
        confirmButtonText: '确认',
        cancelButtonText: '确认',
        type: 'warning',
        showCancelButton : false,
        dangerouslyUseHTMLString: true,
      }
    )
      .then(() => {
        return
        })
      })
      .catch(() => {
        return
      })
      })
      .catch(() => {
        return
      })
    
  }
}
const rollback = (clusterId)=>{
  console.log('cluster id:', clusterId)
  data.clusterId = clusterId
  // data.namespace = namespace
  // data.item.metadata.namespace = namespace
}

onBeforeMount(()=>{

})  
const {options,clusterId} = toRefs(data)

</script>

<template>
  <CreateOrEditFrame
  :show-namespace="false"
  @clusterChangedRollback="rollback"
  >
  <!-- 头部插入内容 -->
<template #header>
  <el-switch v-model="options.method" 
  style="margin-left: 20px; --el-switch-on-color: red; --el-switch-off-color: #13ce66;"
  inline-prompt
  active-text="创建或更新"
  inactive-text="仅创建"
  active-value="Apply"
  inactive-value="Create"
  ></el-switch>
</template>
   <template #main>
    <div>
      <CodeMirror
      v-model="yamlContent"
      height="480px"
      ></CodeMirror>
    </div>
  <div style="margin-top: 10px;">
    <el-button type="primary" @click="submit()">提交</el-button>
  </div>
   </template>

  </CreateOrEditFrame>
</template>

<style scoped>
.button-container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center;     /* 垂直居中（如果需要） */
  gap: 10px;               /* 按钮之间的间距 */
}
</style>
